/**
 * 
 */
package domain;
import java.util.*;

import data.IPeriodDAO;
import data.IProductDAO;
import data.IVoteDAO;
import data.JDBCPeriodDAO;
import data.JDBCProductDAO;
import data.JDBCVoteDAO;

/**
 * @author it-equipment-selection team
 *
 */
public class BallotBox {
	
	private static BallotBox u;
	private Collection votes;
	private boolean votePeriod;

	protected BallotBox() {
		//votes = new LinkedList();
		getVotes();
	}

	public void addVote(User u, Product p) throws Exception {
		if (this.votePeriod){
			boolean find = false;
			Iterator it = votes.iterator();
			while (it.hasNext() && !find){
				Vote v = (Vote) it.next();
				if (v.getUser().getId().compareTo(u.getId()) == 0 && v.getArticle().getCode().compareTo(p.getArticle().getCode())==0)
					find = true;
			}
			if (!find && p.isValid() && !p.isContracted()){
				Vote v = new Vote(u,p);
				votes.add(v);
				//Añadimos el voto a la base de datos
				IVoteDAO vdao = new JDBCVoteDAO(); //ojo acoplamiento -> dao.propierties
				vdao.insert(v);
				p.setNumVotes(p.getNumVotes()+1); 
			} else {
				throw new InvalidVoteException("Invalid vote");
			}
		} else {
			throw new InvalidPeriodException("Vote period not defined");
		}
	}
	
	public Collection getVotes(){
		IVoteDAO vdao = new JDBCVoteDAO(); //ojo acoplamiento -> dao.propierties
		this.votes = vdao.selectAllVotes();
		return votes;
	}

	public boolean isVotePeriod() {
		return votePeriod;
	}

	public void setVotePeriod(boolean votePeriod) {
		this.votePeriod = votePeriod;
		//Actualizar estado en BD
		IPeriodDAO dao = new JDBCPeriodDAO(); //ojo acoplamiento -> dao.propierties
		dao.updatePeriod(votePeriod);
	}	
	
	
	public static synchronized BallotBox getInstance(){
		if (u == null) {
			u = new BallotBox();
		}
		return u;
	}
}
